<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<button onclick="startWs()">开启WebSocket</button>
<button onclick="closeWs()">关闭WebSocket</button>
<br>
<br>
<button onclick="qf(2004)">机场复位</button>
<br>
<button onclick="qf(2006)">自主飞行</button>
<br>
<button onclick="qf(2012)">紧急降落</button>
<br>
<button onclick="qf(2018)">开始起飞</button>
<br>
<br>
<button onclick="qf(2000)">机场准备</button>
<button onclick="qf(2002)">机场急停</button>
<script>
    // let airportId = 100
    // let userId = 112;
    let airportId = 1001 // 机场ID 1001 航线 457
    let userId = 2;
    let userToken = 'pBkfXCqGGqsNvOMTRjxS';
    let routeId = 136

    function startWs() {
        if (window.mws && window.mws.readyState === window.mws.OPEN){
            console.log('当前已存在 WebSocket 对象，无需再次开启连接')
            return;
        }


        // window.mws = new WebSocket(`ws://116.63.231.235:8088/ws/asset/v4/${userId}/${userToken}`)
        window.mws = new WebSocket(`ws://foyoung.f3322.net:8094/ws/asset/v4/${userId}/${userToken}`)
        mws.CLOSED
        mws.onopen = function (args) {
            console.log('onopen', args)
        }
        mws.onmessage = function (args) {
            console.log('onmessage', JSON.parse(args.data))
        }
        mws.onerror = function (args) {
            console.log('onerror', args)
        }
        mws.onclose = function (args) {
            console.log('onclose', args)
        }
    }


    function closeWs() {
        if (!window.mws) {
            console.log('暂无待关闭的 WebSocket')
            return
        }
        const status = mws.readyState;
        switch (status) {
            case mws.OPEN:
                mws.close();
                break
            case mws.CLOSED:
                console.log('该 WebSocket 已关闭')
                break
            case mws.CLOSING:
                console.log('该 WebSocket 正在关闭')
                break
            default:
                console.log(`未知的 WebSocket 状态：${status}`)
        }
    }

    // 起飞
    function qf(code) {
        if (mws) {
            mws.send(JSON.stringify({
                'deviceId': airportId,
                'msgType': code
            }))
        }
    }
</script>
</body>
</html>